/*
 * SPDX-FileCopyrightText: 2010-2022 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: CC0-1.0
 */
#include "board.h"
#include "cmd_process.h"
#include "driver/uart.h"
#include "esp_chip_info.h"
#include "esp_err.h"
#include "esp_flash.h"
#include "esp_heap_caps.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "sdkconfig.h"
#include "user_bt.h"
#include "user_camera.h"
#include "user_codec.h"
#include "user_fs.h"
#include "user_gpio.h"
#include "user_utils.h"
#include "user_wifi.h"
#include <inttypes.h>
#include <stdio.h>

#define TAG "open glass"

static void reconfigure_debug_uart();

void app_main(void) {
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }

    reconfigure_debug_uart();

    update_devInfo();

    /* Initialize LittleFS */
    if (user_fs_init() != ESP_OK) {
        ESP_LOGI(TAG, "Failed to initialize LittleFS");
    }

#ifdef CONFIG_AIGLASS_V1_1_BOARD
    // user_gpio_init();
#endif

    user_codec_init();

    // // init_camera();

    user_wifi_init();

    ble_init();

    user_bt_init();

    // 录音线程
    xTaskCreatePinnedToCore(record_task, "record_task", 3072, NULL, 5, NULL, 1);

    xTaskCreatePinnedToCore(player_task, "player_task", 4096, NULL, 5, NULL, 1);

    // 等待音频线程启动
    vTaskDelay(500 / portTICK_PERIOD_MS);

    cmd_process_init();

    // opus_test();

    while (1) {
        // get_capture("/littlefs/capture.jpeg");
        ESP_LOGI("MEM", "Free DRAM (INTERNAL): %d bytes", heap_caps_get_free_size(MALLOC_CAP_INTERNAL));
        ESP_LOGI("MEM", "Free PSRAM (SPIRAM): %d bytes", heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
        vTaskDelay(10000 / portTICK_PERIOD_MS);
    }
}

#define TX_PIN 1
#define RX_PIN UART_PIN_NO_CHANGE // 禁用接收引脚
void reconfigure_debug_uart() {
    uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };

    uart_param_config(UART_NUM_0, &uart_config);
    uart_set_pin(UART_NUM_0, TX_PIN, RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
    uart_driver_install(UART_NUM_0, 256, 0, 0, NULL, 0);
}